#include <jni.h>
#include <string>
#include "BikeCommandUtil.h"  // 包含头文件
#include "WorkoutDataHandler.h"

extern "C"
JNIEXPORT jstring JNICALL
Java_com_oem_qisda_BikeAPI_parseCommand(JNIEnv *env, jobject thiz, jstring command) {
    // 将 Java 字符串转换为 C++ 字符串
    const char *nativeCommand = env->GetStringUTFChars(command, 0);

    // 调用你已有的 C++ 函数
    std::string result = BikeCommandUtil::parseCommand(std::string(nativeCommand));

    // 释放 Java 字符串资源
    env->ReleaseStringUTFChars(command, nativeCommand);

    // 将 C++ 字符串结果返回为 Java 字符串
    return env->NewStringUTF(result.c_str());
}
//
//extern "C" JNIEXPORT jstring JNICALL
//Java_com_oem_qisda_BikeAPI_serializeWorkoutData(JNIEnv* env, jobject) {
//    WorkoutDataHandler& handler = WorkoutDataHandler::getInstance();
//    std::string serializedData = handler.serializeWorkoutDataToString();
//    return env->NewStringUTF(serializedData.c_str());
//}

extern "C" JNIEXPORT jbyteArray JNICALL
Java_com_oem_qisda_BikeAPI_serializeWorkoutData(JNIEnv* env, jobject) {
    WorkoutDataHandler& handler = WorkoutDataHandler::getInstance();
    std::string serializedData = handler.serializeWorkoutDataToString();

    // 创建 jbyteArray 并将 C++ 字符串内容复制到 jbyteArray
    jbyteArray byteArray = env->NewByteArray(serializedData.size());
    env->SetByteArrayRegion(byteArray, 0, serializedData.size(), reinterpret_cast<const jbyte*>(serializedData.c_str()));

    return byteArray;
}

//extern "C" JNIEXPORT jboolean JNICALL
//Java_com_oem_qisda_BikeAPI_deserializeWorkoutData(JNIEnv* env, jobject, jstring data) {
//    const char* nativeData = env->GetStringUTFChars(data, 0);
//    WorkoutDataHandler& handler = WorkoutDataHandler::getInstance();
//    bool res = handler.deserializeWorkoutDataFromString(nativeData);
//    env->ReleaseStringUTFChars(data, nativeData);
//    return res ? JNI_TRUE : JNI_FALSE;
//}


extern "C" JNIEXPORT jboolean JNICALL
Java_com_oem_qisda_BikeAPI_deserializeWorkoutData(JNIEnv* env, jobject, jbyteArray data) {
    jsize length = env->GetArrayLength(data);
    jbyte* nativeData = env->GetByteArrayElements(data, 0);

    WorkoutDataHandler& handler = WorkoutDataHandler::getInstance();
    bool res = handler.deserializeWorkoutDataFromString(std::string(reinterpret_cast<char*>(nativeData), length));

    env->ReleaseByteArrayElements(data, nativeData, 0);
    return res ? JNI_TRUE : JNI_FALSE;
}

extern "C" JNIEXPORT jboolean JNICALL
Java_com_oem_qisda_BikeAPI_isWorkoutDataEmpty(JNIEnv* env, jobject) {
    // 获取 WorkoutDataHandler 的单例
    WorkoutDataHandler& handler = WorkoutDataHandler::getInstance();

    // 调用 isWorkoutDataEmpty 函数并返回结果
    bool isEmpty = handler.isWorkoutDataEmpty();

    return isEmpty ? JNI_TRUE : JNI_FALSE;
}
